import pymongo
from bson import ObjectId
from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.database import Database

client: MongoClient | None = None
db: Database | None = None
user: Collection | None = None
chat: Collection | None = None


def initMongo():
    """
    创建并打开 MongoDB 数据库
    client: 数据库客户端
    db: 数据库
    user: 用户信息表
    chat: 聊天信息表
    """
    global client, db, user, chat
    client = pymongo.MongoClient('localhost', 27017)
    db = client['MyWeDb']
    # user 数据集合：用户信息
    user = db['user']
    # chatinfotemp 数据集合：临时保存的聊天信息
    chat = db['chatinfotemp']


def addUsers(users: list):
    user.insert_many(users)


def isUserOnline(username: str) -> bool:
    return user.find_one({"Username": username})['Online']


def setUserOnline(username: str, online: bool):
    user.update_one({"Username": username}, {"$set": {"Online": online}})


def getUserFocuses(username: str) -> list:
    return user.find_one({"Username": username})['Focus']


def getReceivedMessages(username: str) -> list:
    return list(chat.find({"Username": username}))


def delSavedMessages(mid):
    chat.delete_one({"_id": mid})


def saveMessage(data):
    chat.insert_one(data)


def closeMongo():
    """
    关闭数据库
    """
    client.close()
